package com.yyr.callmessage.core.util;

import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;

@Slf4j
public class IpUtil {
    /**
     * 获取登录用户的IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    private static DbSearcher _searcher;

    static {
        try {
            ClassPathResource resource = new ClassPathResource("/ip2region.db");
            if (resource.getClassLoader() == null) {
                log.error("存储路径发生错误，没有被发现");
            }
            InputStream inputStream = resource.getInputStream();
            byte[] dbBinStr = FileUtil.readInputStream(inputStream);
            _searcher = new DbSearcher(new DbConfig(), dbBinStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ip转区域
     * @param ip
     * @return
     */
    public static String getRegionByIp(String ip) {
        try {
            //获取出来的格式如 中国|0|广东|深圳|鹏博士
            DataBlock fdata = _searcher.memorySearch(ip);
            if (fdata != null) {
                List<String> fromRegion = Splitter.on("|").omitEmptyStrings().trimResults().splitToList(fdata.getRegion());
                String region = "";
                if (!CollectionUtils.isEmpty(fromRegion)) {
                    region = fromRegion.get(0) + "-" + fromRegion.get(2);
                }
                return region;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
